package com.wan.activity;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import com.alipay.sdk.app.PayTask;
import com.reyun.sdk.ReYunTrack;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.Keys;
import com.wan.commonsdk.MD5Utils;
import com.wan.commonsdk.PayInfo;
import com.wan.commonsdk.PayResult;
import com.wan.commonsdk.Rsa;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.YHQInfo;
import com.wan.task.PayOrderidTask;
import com.wan.task.PayYHQTask;
import com.wan.taskListener.PayOrderYHQTaskListener;

import net.sourceforge.simcpux.Util;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Pay_Order_Activity extends BaseActivity implements OnClickListener {
	private RelativeLayout order_youhui_rel;
	private ImageView order_alipay_yimg, order_wx_yimg, order_yl_yimg;
	private Intent intent;
	private PayInfo payInfo;
	private String orderid;
	private static final int RQF_PAY = 1;
	private static final int WAN_TRADE = 2;
	private static final int WX_PREORDER = 5;
	private static final int WX_PAY = 6;
	private static final int PAYUP_FAILURE = 0;
	private static final int ALIPAY = 19;
	private static final int ORDER_FAIL = 11;
	private static final int WEIXIN = 1013;
	ArrayList<YHQInfo> list;
	PayReq req;
	IWXAPI msgApi;
	StringBuffer sb;
	Map<String, String> resultunifiedorder;
	private TextView pay_order_money, order_yhq_number, order_bootom_price_tx;

	private TextView pay_gamemoney, pay_uname, pay_number, order_back_btn,
			order_yhq_rule;

	private String money;

	private Dialog dialog;

	private boolean bbn = true;
	private void isbind_dialog() {

		if (Conet.mUserInfo.isGuest()

		) {
			dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setCancelable(false);// 设置点击屏幕Dialog不消失
			dialog.setContentView(Util.getResID("guest_bind_dialog", "layout"));

			dialog.findViewById(Util.getResID("bind_dialog_btn", "id"))
					.setOnClickListener(this);

			dialog.findViewById(Util.getResID("bind_dialog_yh", "id"))
					.setOnClickListener(this);

			dialog.findViewById(Util.getResID("bind_dialog_close", "id"))
					.setOnClickListener(this);
			dialog.show();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_order_activity", "layout"));
		String a = android.os.Build.VERSION.RELEASE;
		int b = Integer.parseInt(a.substring(0, 1));
//		if(b<5){
//			bbn = false;
//			findViewById(Util.getResID("weixin_pay", "id")).setVisibility(View.GONE);
//		}else{
//			bbn = true;
//			
//		} //COK 4.x  版本错误
		req = new PayReq();

		Log.e("weixin req",req.toString()+"********");
		msgApi = WXAPIFactory.createWXAPI(this, null);
		init();
	}

	private void init() {
		Conet conet = Conet.getInstance();
		conet.addActivity(this);
		isbind_dialog();
		intent = getIntent();
		payInfo = (PayInfo) intent.getSerializableExtra("payinfo");
		payInfo.setTradename("支付宝客户端");
		payInfo.setTradeid(ALIPAY + "");
		
		sb = new StringBuffer();

		pay_gamemoney = (TextView) findViewById(Util.getResID("pay_gamemoney",
				"id"));

		pay_gamemoney.setText(payInfo.getItemname());
		pay_uname = (TextView) findViewById(Util.getResID("pay_uname", "id"));
		pay_uname.setText(Conet.mUserInfo.getUser_name());
		pay_number = (TextView) findViewById(Util.getResID("pay_number", "id"));
		pay_number.setText("￥" + payInfo.getFixedmoney());
		order_bootom_price_tx = (TextView) findViewById(Util.getResID(
				"order_bootom_price_tx", "id"));
		pay_order_money = (TextView) findViewById(Util.getResID(
				"pay_order_money", "id"));
		int prder_money = Integer.parseInt(payInfo.getFixedmoney());
		if (payInfo.getYhqInfo() != null) {

			double price = Double.parseDouble(payInfo.getYhqInfo().getPrice());
			int priceint = (int) price;
			order_bootom_price_tx.setText(priceint + "");
			prder_money = ((Integer.parseInt(payInfo.getFixedmoney()) - priceint));
		}

		pay_order_money.setText("总计 ￥" + prder_money);
		money = prder_money + "";

		order_yhq_number = (TextView) findViewById(Util.getResID(
				"order_yhq_number", "id"));
		String order_yhq_tx = "优惠券";
		if (payInfo.getYhqInfo() != null
				&& !"0".equals(payInfo.getYhqInfo().getPrice())) {
			order_yhq_tx = payInfo.getYhqInfo().getPrice();
			order_yhq_number.setText("￥" + order_yhq_tx);
		} else {
			order_yhq_number.setText(order_yhq_tx);
		}
		order_youhui_rel = (RelativeLayout) findViewById(Util.getResID(
				"order_youhui_rel", "id"));
		order_youhui_rel.setOnClickListener(this);
		order_alipay_yimg = (ImageView) findViewById(Util.getResID(
				"order_alipay_yimg", "id"));
		order_alipay_yimg.setOnClickListener(this);
		order_alipay_yimg.setTag(true);
		order_wx_yimg = (ImageView) findViewById(Util.getResID("order_wx_yimg",
				"id"));
		order_wx_yimg.setOnClickListener(this);
		order_wx_yimg.setTag(false);
		order_yl_yimg = (ImageView) findViewById(Util.getResID("order_yl_yimg",
				"id"));
		order_yl_yimg.setOnClickListener(this);
		order_yl_yimg.setTag(false);
		RelativeLayout wan51_order_bootom_right = (RelativeLayout) findViewById(Util
				.getResID("wan51_order_bootom_right", "id"));
		wan51_order_bootom_right.setOnClickListener(this);
		order_back_btn = (TextView) findViewById(Util.getResID(
				"order_back_btn", "id"));
		order_back_btn.setOnClickListener(this);

		order_yhq_rule = (TextView) findViewById(Util.getResID("order_yhq_tx",
				"id"));
		order_yhq_rule.setOnClickListener(this);

//		PayYHQTask paytask = new PayYHQTask(payInfo, 1); //优惠券  暂停使用
//		paytask.setYhqListener(morder_yhqlistener);
//		showLoading();
//		paytask.execute();

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case RQF_PAY:
				hideLoading();
				PayResult payResult = new PayResult((String) msg.obj);
				// String resultInfo = payResult.getResult();
				String resultStatus = payResult.getResultStatus();
				int success = 1;
				// Util.LogUtil("--------------result:" + payResult);
				if (TextUtils.equals(resultStatus, "9000")) {
					success = 0;
					
					WanCommonSdk.payupcallBack.onComplete(success);
					showHint("支付成功");
//					TrackingIO.setPayment(orderid, "alipay", "CNY", Integer.parseInt(money));
					ReYunTrack.setPayment(orderid, "alipay", "CNY", Integer.parseInt(money));
					finish();
				} else {
					showHint("支付失败");
					WanCommonSdk.payupcallBack.onComplete(1);
					finish();
				}
				break;

			case WX_PAY:
					hideLoading();
					showLoading("正在进行微信充值跳转.......");
					Log.e("LOGWEIXIN", "WX_PAY --result:" + resultunifiedorder);
					
					req.prepayId= resultunifiedorder.get("prepay_id");
					req.packageValue = "Sign=WXPay";
					req.nonceStr = MD5Utils.getMessageDigest(String.valueOf(
							new Random().nextInt(10000)).getBytes());
					req.timeStamp = String
							.valueOf(System.currentTimeMillis() / 1000);
					List<NameValuePair> signParams = new LinkedList<NameValuePair>();
					signParams.add(new BasicNameValuePair("appid", req.appId));
					signParams
							.add(new BasicNameValuePair("noncestr", req.nonceStr));
					signParams.add(new BasicNameValuePair("package",
							req.packageValue));
					signParams.add(new BasicNameValuePair("partnerid",
							req.partnerId));
					signParams
							.add(new BasicNameValuePair("prepayid", req.prepayId));
					signParams.add(new BasicNameValuePair("timestamp",
							req.timeStamp));
					req.sign = genAppSign(signParams, Keys.WX_API_KEY);
					// sb.append("sign\n" + req.sign + "\n\n");
					// Log.e("LOGwww123", "pay sign:" + sb.toString());
					msgApi.sendReq(req);
					hideLoading();
				break;
			}

		};

	};
	private PayOrderYHQTaskListener morder_yhqlistener = new PayOrderYHQTaskListener() {

		@Override
		public void yhq_result(Object object) {
			hideLoading();
			list = (ArrayList<YHQInfo>) object;
			if (payInfo.getYhqInfo() == null) {
				if (list != null && list.size() > 0) {
					if ("1".equals(list.get(0).getCheck())) {
						order_yhq_number.setText("有可用优惠券");
					}else{
						order_yhq_number.setText("暂无可用优惠券");
					}
				} else {
					order_yhq_number.setText("暂无可用优惠券");
				}
			}
		}
		@Override
		public void payOrderid(PayInfo payinfo, String orderid) {
			if (orderid != null && !"".equals(orderid)) {
				hideLoading();
				Pay_Order_Activity.this.orderid = orderid;
				
				
				if (payinfo.getTradeid().equals(ALIPAY + "")) {
//					TrackingIO.setPaymentStart(orderid, "alipay", "CNY", Integer.parseInt(money));
					ReYunTrack.setPaymentStart(orderid, "alipay", "CNY", Integer.parseInt(money));
					String info = getOrderInfo();
					String sign = Rsa.sign(info, Keys.NEW_PRIVATE);
					try {
						// 仅需对sign 做URL编码
						sign = URLEncoder.encode(sign, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					info += "&sign=\"" + sign + "\"&" + getSignType();

					final String orderInfo = info;

					new Thread(new Runnable() {

						@Override
						public void run() {
							PayTask alipay = new PayTask(
									Pay_Order_Activity.this);
							String result = alipay.pay(orderInfo);

							Message msg = new Message();
							msg.what = RQF_PAY;
							msg.obj = result;
							mHandler.sendMessage(msg);
							Log.e("Alipay", result);

						}
					}).start();
				} else if (payinfo.getTradeid().equals(WEIXIN + "")) {
						hideLoading();
//						TrackingIO.setPaymentStart(orderid, "weixinpay", "CNY", Integer.parseInt(money));
						ReYunTrack.setPaymentStart(orderid, "weixinpay", "CNY", Integer.parseInt(money));
						Editor edit = Conet.TrackingIOSP.edit();
						edit.putString("orderid", orderid);
						edit.putString("money", money);
						edit.commit();
						Log.e("weixin  appid", Keys.WX_APP_ID+"------------");
						req.appId = Keys.WX_APP_ID;
						req.partnerId = Keys.WX_MCH_ID;
						msgApi.registerApp(Keys.WX_APP_ID);
						WEIXINPrepayIdTask getPrepayId = new WEIXINPrepayIdTask();
						getPrepayId.execute();

				}
			} else {
				hideLoading();
				Toast.makeText(getApplicationContext(), "订单号获取失败，检查网络",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == Util.getResID("order_youhui_rel", "id")) {
			Intent intent = new Intent(Pay_Order_Activity.this,
					WanYHListActivity.class);
			if (list != null && list.size() > 0) {

				intent.putExtra("list", list);
			}
			intent.putExtra("payinfo", payInfo);
			startActivity(intent);
			finish();
		} else if (v.getId() == Util.getResID("order_alipay_yimg", "id")) {
			boolean isAlipay = (Boolean) order_alipay_yimg.getTag();
			if (isAlipay) {
				order_alipay_yimg.setTag(false);
				order_alipay_yimg.setBackgroundResource(Util.getResID(
						"wan51_fu", "drawable"));
			} else {
				order_alipay_yimg.setBackgroundResource(Util.getResID(
						"wan51_ed", "drawable"));
				order_alipay_yimg.setTag(true);
				payInfo.setTradename("支付宝客户端");
				payInfo.setTradeid(ALIPAY + "");
				order_wx_yimg.setTag(false);
				order_wx_yimg.setBackgroundResource(Util.getResID("wan51_fu",
						"drawable"));
				order_yl_yimg.setTag(false);
				order_yl_yimg.setBackgroundResource(Util.getResID("wan51_fu",
						"drawable"));
			}
		} else if (v.getId() == Util.getResID("order_wx_yimg", "id")) {
			boolean isAlipay = (Boolean) order_wx_yimg.getTag();
			if (isAlipay) {
				order_wx_yimg.setTag(false);
				order_wx_yimg.setBackgroundResource(Util.getResID("wan51_fu",
						"drawable"));
			} else {
				order_wx_yimg.setBackgroundResource(Util.getResID("wan51_ed",
						"drawable"));
				order_wx_yimg.setTag(true);
				payInfo.setTradename("微信支付");
				payInfo.setTradeid(WEIXIN + "");
				order_alipay_yimg.setTag(false);
				order_alipay_yimg.setBackgroundResource(Util.getResID(
						"wan51_fu", "drawable"));
				order_yl_yimg.setTag(false);
				order_yl_yimg.setBackgroundResource(Util.getResID("wan51_fu",
						"drawable"));

			}
		} else if (v.getId() == Util.getResID("wan51_order_bootom_right", "id")) {

			PayOrderidTask payordertask = new PayOrderidTask(payInfo);
			payordertask.setYhqListener(morder_yhqlistener);
			showLoading();
			payordertask.execute();

		} else if (v.getId() == Util.getResID("order_yl_yimg", "id")) {
			boolean isAlipay = (Boolean) order_yl_yimg.getTag();
			if (isAlipay) {
				order_yl_yimg.setTag(false);
				order_alipay_yimg.setBackgroundResource(Util.getResID(
						"wan51_fu", "drawable"));
			} else {
				order_yl_yimg.setBackgroundResource(Util.getResID("wan51_ed",
						"drawable"));
				order_yl_yimg.setTag(true);
				order_alipay_yimg.setTag(false);
				order_alipay_yimg.setBackgroundResource(Util.getResID(
						"wan51_fu", "drawable"));
				order_wx_yimg.setTag(false);
				order_wx_yimg.setBackgroundResource(Util.getResID("wan51_fu",
						"drawable"));
			}
		} else if (v.getId() == Util.getResID("order_back_btn", "id")) {
			
			try{
			WanCommonSdk.payupcallBack.onComplete(1);
			}catch(Exception e){
				e.printStackTrace();
			}
			finish();
		
		
		} else if (v.getId() == Util.getResID("order_yhq_tx", "id")) {
			Intent intent = new Intent(Pay_Order_Activity.this,
					WANRuleActivity.class);
			startActivity(intent);
		} else if (v.getId() == Util.getResID("bind_dialog_btn", "id")) {
			Intent intent = new Intent(Pay_Order_Activity.this,
					guest_userbind.class);
			startActivity(intent);
			dialog.dismiss();
		} else if (v.getId() == Util.getResID("bind_dialog_yh", "id")
				|| v.getId() == Util.getResID("bind_dialog_close", "id")) {
			dialog.dismiss();
		}

	}

	public String getOrderInfo() {
		StringBuffer orderInfo = new StringBuffer("partner=" + "\""
				+ Keys.NEW_PARTNER + "\"");
		; // 签约合作者身份ID
		orderInfo.append("&seller_id=" + "\"" + Keys.NEW_SELLER + "\""); // 签约卖家支付宝账号
		orderInfo.append("&out_trade_no=" + "\"" + orderid + "\""); // 商户网站唯一订单号
		// Log.e("tradeno",payInfo.getTradeno()+"" );
		orderInfo.append("&subject=" + "\"" + payInfo.getSubject() + "\""); // 商品名称
		orderInfo.append("&body=" + "\"" + payInfo.getBody() + "\""); // 商品详情
		orderInfo.append("&total_fee=" + "\"" + money + "\""); // 商品金额
		orderInfo.append("&notify_url=" + "\"" + Conet.ALIPAY_URL + "\""); // 服务器异步通知页面路径
		orderInfo.append("&service=\"mobile.securitypay.pay\""); // 服务接口名称， 固定值  
		orderInfo.append("&payment_type=\"1\""); // 支付类型， 固定值
		orderInfo.append("&_input_charset=\"utf-8\""); // 参数编码， 固定值
		orderInfo.append("&it_b_pay=\"3m\"");
		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo.append("&return_url=\"m.alipay.com\"");
		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";
		Util.LogUtil("pay:" + orderInfo);
		return orderInfo.toString();
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();
		Random random = new Random();

		String nonceStr = MD5Utils.getMessageDigest(String.valueOf(
				random.nextInt(10000)).getBytes());


		xml.append("</xml>");
		List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
		packageParams.add(new BasicNameValuePair("appid", Keys.WX_APP_ID));
		packageParams.add(new BasicNameValuePair("body", payInfo.getBody()));
		Log.e("weixin body",payInfo.getBody());
		packageParams.add(new BasicNameValuePair("mch_id", Keys.WX_MCH_ID));
		packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
		packageParams.add(new BasicNameValuePair("notify_url",
				Conet.WX_NOTIFIY_URL));
		packageParams.add(new BasicNameValuePair("out_trade_no", orderid));
		packageParams.add(new BasicNameValuePair("spbill_create_ip",
				"127.0.0.1"));
		int fix = Integer.parseInt(money) * 100;
		packageParams.add(new BasicNameValuePair("total_fee", fix + ""));
		packageParams.add(new BasicNameValuePair("trade_type", "APP"));
		String sign = genPackageSign(packageParams);
		packageParams.add(new BasicNameValuePair("sign", sign));
		String xmlstring = toXml(packageParams);
		String a = "";
		try {
			a = new String(xmlstring.toString().getBytes("UTF-8"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return a;

	}
	public  String getEncoding(String str) {        
	       String encode = "GB2312";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s = encode;        
	              return s;        
	           }        
	       } catch (Exception exception) {        
	       }        
	       encode = "ISO-8859-1";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s1 = encode;        
	              return s1;        
	           }        
	       } catch (Exception exception1) {        
	       }        
	       encode = "UTF-8";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s2 = encode;        
	              return s2;        
	           }        
	       } catch (Exception exception2) {        
	       }        
	       encode = "GBK";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s3 = encode;        
	              return s3;        
	           }        
	       } catch (Exception exception3) {        
	       }  
	    return "";   
	   }    
	private String genAppSign(List<NameValuePair> params, String key) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(key);

		this.sb.append("sign str\n" + sb.toString() + "\n\n");
		String appSign = MD5Utils.getMessageDigest(sb.toString().getBytes())
				.toUpperCase();
		Util.LogUtil(appSign);
		return appSign;
	}

	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");

			sb.append(params.get(i).getValue());
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");
		Util.LogUtil(sb.toString());
		return sb.toString();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		pay_uname.setText(Conet.mUserInfo.getUser_name());
	}
	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Keys.WX_API_KEY);
		Util.LogUtil("sb:" + sb.toString());
		
		
//		sb:appid=wxd52ddb5f90a36adf&body=6000金币礼包&mch_id=1297844401&nonce_str=a82d922b133be19c1171534e6594f754&notify_url=http://pay.51wan.com/channel/wechatpay/topay/notify.php&out_trade_no=XY2876608383352&spbill_create_ip=127.0.0.1&total_fee=12800&trade_type=APP&key=e4933bf9d7c3605d625ffe9ebaddf34b
//		sb:appid=wxd52ddb5f90a36adf&body=500金币礼包&mch_id=1297844401&nonce_str=f3bd5ad57c8389a8a1a541a76be463bf&notify_url=http://pay.51wan.com/channel/wechatpay/topay/notify.php&out_trade_no=XY3551962135148&spbill_create_ip=127.0.0.1&total_fee=600&trade_type=APP&key=e4933bf9d7c3605d625ffe9ebaddf34b
//		sb:appid=wxd52ddb5f90a36adf&body=body&mch_id=1297844401&nonce_str=142949df56ea8ae0be8b5306971900a4&notify_url=http://pay.51wan.com/channel/wechatpay/topay/notify.php&out_trade_no=XY1433736670654&spbill_create_ip=127.0.0.1&total_fee=100&trade_type=APP&key=e4933bf9d7c3605d625ffe9ebaddf34b
		
		
		String packageSign = MD5Utils
				.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Util.LogUtil(packageSign);
		return packageSign;
	}

	public Map<String, String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName = parser.getName();
				switch (event) {
				case XmlPullParser.START_DOCUMENT:

					break;
				case XmlPullParser.START_TAG:

					if ("xml".equals(nodeName) == false) {
						// 实例化student对象
						xml.put(nodeName, parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				event = parser.next();
			}
			Util.LogUtil("xml:" + xml);
			return xml;
		} catch (Exception e) {
			Util.LogUtil(e.toString());
		}
		return null;

	}

	private class WEIXINPrepayIdTask extends
			AsyncTask<Void, Void, Map<String, String>> {

		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			Log.d("LOG", "weixin preexecute:" + sb.toString());
			dialog = ProgressDialog.show(Pay_Order_Activity.this, "提示",
					"正在获取预支付订单...");
		}

		@Override
		protected void onPostExecute(Map<String, String> result) {
			Util.LogUtil("onPostExecute:");
			if (dialog != null) {
				dialog.dismiss();
			}
			sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
			Util.LogUtil("weixin:" + result);
			resultunifiedorder = result;

			Message msg = new Message();
			msg.what = WX_PAY;
			mHandler.sendMessage(msg);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String, String> doInBackground(Void... params) {

			String url = String
					.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();

			Util.LogUtil("entity:" + entity);
			byte[] buf = Util.httpPost(url, entity);

			String content = new String(buf);
			Util.LogUtil("weixin content:" + content);
			Map<String, String> xml = decodeXml(content);
			return xml;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return false;
	}
}
